package com.xs.tool.common.utils.jaxb;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.Marshaller;
import java.lang.reflect.Field;
//监听生成xml文件过程
public class MarshallerListener extends Marshaller.Listener {

    private static Logger logger = LoggerFactory.getLogger(MarshallerListener.class);
    public static final String BLANK_CHAR = "";

    @Override
    public void beforeMarshal(Object source) {
        super.beforeMarshal(source);
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                logger.debug(f.getType() + f.getName());
                if (f.getType() == String.class && f.get(source) == null) {
                    f.set(source, BLANK_CHAR);
                }else if(!isBaseType(f)&& f.get(source) != null){
                    beforeMarshalClass(f.get(source));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    private void beforeMarshalClass(Object source) {
        // TODO Auto-generated method stub
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            try {
                if (f.getType() == String.class && f.get(source) == null) {
                    f.set(source, BLANK_CHAR);
                }else if(!isBaseType(f) && f.get(source) != null){
                    logger.debug(f.getType()+f.getName());
                    beforeMarshalClass(f.get(source));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断object是否为基本类型
     * @param object
     * @return
     */
    public static boolean isBaseType(Field f) {
        logger.debug(""+f.getType());
        logger.debug(""+String.class);
        logger.debug(""+(f.getType() == String.class));
        if (f.getType() == Integer.class ||
                f.getType() == Byte.class ||
                f.getType() == Long.class ||
                f.getType() == Double.class ||
                f.getType() == String.class ||
                f.getType() == Float.class ||
                f.getType() == Character.class ||
                f.getType() == Short.class ||
                f.getType() == Boolean.class) {
            return true;
        }
        return false;
    }
}
